#蓝本中定义的程序路由
from datetime import datetime
from flask import render_template,session,redirect,url_for,request,flash
from ..models import Device,RentDevice  

from . import main
from .forms import NameForm
from ..import db
from ..models import User
from flask_login import current_user
import arrow
from sqlalchemy import and_

@main.route('/',methods=['GET','POST'])
def index():
    form=NameForm()
    if form.validate_on_submit():
        # ...
        return redirect(url_for('.index'))
    return render_template('index.html',
                            form=form,name=session.get('name'),
                            known=session.get('known',False),
                            current_time=datetime.utcnow())

@main.route('/devicesList')
def devicesList():
    devices=Device.query.all() 
    return render_template('devicesList.html',list=devices)

#查询设备
@main.route('/queryDevice',methods=['GET','POST'])
def queryDevice():
    device_name=request.form['device_name']
    devices=Device.query.filter_by(device_name=device_name).all() 

    if devices:
        return render_template('devicesList.html',list=devices)
    else:
        return "您查询的设备不存在"

#租借设备
@main.route('/rentDevice')
def rentDevice():
    deviceid=request.args.get('id')
    rentdevice=db.session.query(RentDevice).filter(and_(RentDevice.deviceid==deviceid,RentDevice.status==1)).first()
    if rentdevice:
        return "该设备已借出"
    else:
        userid=current_user.id
        rent_time=arrow.now().timestamp
        back_time=arrow.now().timestamp+604800
        actual_time=arrow.now().timestamp
        status=1
        rentdevice=RentDevice(userid=userid,deviceid=deviceid,
                                rent_time=rent_time,back_time=back_time,
                                actual_time=actual_time,status=status)
        db.session.add(rentdevice)
        return "租借成功"

#用户租借列表
@main.route('/rentlist')
def rentlist():
    devices=db.session.query(Device).join(RentDevice,and_(RentDevice.userid==current_user.id,RentDevice.deviceid==Device.id,RentDevice.status==1)).all()
    return render_template('rentlist.html',list=devices)

#签还设备
@main.route('/backDevice')
def backDevice():
    deviceid=request.args.get('id')
    rentdevice=db.session.query(RentDevice).filter(and_(RentDevice.deviceid==deviceid,RentDevice.status==1,RentDevice.userid==current_user.id)).first()
    rentdevice.status=0
    return redirect(url_for('main.rentlist'))
